import copy
import P0120_生成后缀表达式_token表示 as P0120
import json


# 遍历token列表，将后缀表达式创建为树结构
def InfixToTree(tokens):
    """
    将后缀表达式转化为表达式树    
    Args:
        tokens (list): 每个元素为一个字典，包含"type"和"word"两个键，分别表示token的类型和值    
    Returns:
        dict: 表达式树的根节点，为一个字典，包含"tag"、"data"和"children"三个键，分别表示节点的标签、数据和子节点列表
    """
    stack = []
    length = len(tokens)
    for i in range(length):
        token = tokens[i]
        if token["type"] == "TOKEN_TYPE_OPERATOR":
            right_child = stack.pop()
            left_child = stack.pop()
            node = {
                "tag": token["word"],
                "data": token,
                "children": [left_child, right_child],
            }
            stack.append(node)
        if token["type"] == "TOKEN_TYPE_NUMBER":
            node = {"tag": token["word"], "data": token, "children": []}
            stack.append(node)
    return stack[0]


if __name__ == "__main__":
    expression = []
    expression.append("3+4*2*(1+5)^2^3")
    for i in range(len(expression)):
        print("第%d个表达式:" % (i + 1))
        print(expression[i])
        tokens = P0120.Tokenize(expression[i])
        for token in tokens:
            print(token["word"] + ", " + token["type"])
        rst = P0120.SyntaxAnalyzer(tokens)
        print(f"{expression[i]}语法分析结果:\n{rst}")
        if rst == True:
            postfixExpTokens = P0120.InfixToPostfix(tokens)
            print("后缀表达式:")
            for token in postfixExpTokens:
                print(token)
            tree = InfixToTree(postfixExpTokens)
            # 将字典转换为 JSON 字符串
            json_tree = json.dumps(tree, indent=4)
            print(json_tree)
